import { addUser, deleteUser, editUser, getUserList } from '@/services/account';
import { getAllRoleList } from '@/services/roles';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';
import { message, Modal, Tag } from 'antd';
// import { Input } from "antd";
import { useEffect, useRef, useState } from 'react';
import AddUserModal from './addUserModal';
import EditUserModal from './editUserModal';

const UsersManage: React.FC<any> = () => {
  const [roleListMap, setAllRoleMap] = useState<Record<string, ROLE.RoleType>>({});
  const actionRef = useRef<ActionType>();

  const loadAllRole = () => {
    getAllRoleList().then((res) => {
      if (res.success) {
        setAllRoleMap(
          res.data.reduce(
            (result: Record<string, ROLE.RoleType>, cur: ROLE.RoleType) => ({
              ...result,
              [cur.id]: cur,
            }),
            {},
          ),
        );
      }
    });
  };

  useEffect(() => {
    loadAllRole();
  }, []);

  const delUser = (id: string) => {
    Modal.confirm({
      title: '温馨提示',
      content: '确定删除该用户吗？',
      okType: 'danger',
      async onOk() {
        return deleteUser({ id }).then((res) => {
          if (res.success) {
            message.success('删除成功');
            actionRef.current?.reload();
          }
        });
      },
    });
  };

  const onAddUser = (value: SYSTEMUSER.AddRoleParams) => {
    const hideMessageLoading = message.loading('处理中...', 0);
    addUser(value)
      .then((res) => {
        if (res.success) {
          message.success('添加成功');
          actionRef.current?.reload();
        }
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        hideMessageLoading();
      });
  };

  const onEditUser = (value: SYSTEMUSER.EditRoleParams) => {
    const hideMessageLoading = message.loading('处理中...', 0);
    editUser(value)
      .then((res) => {
        if (res.success) {
          message.success('修改成功');
          actionRef.current?.reload();
        }
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        hideMessageLoading();
      });
  };

  const columns: ProColumns<SYSTEMUSER.UserType>[] = [
    {
      title: '序号',
      width: 80,
      valueType: 'index',
    },
    {
      title: '用户名',
      dataIndex: 'userName',
    },
    {
      title: '用户密码',
      dataIndex: 'userPassword',
      valueType: 'password',
      hideInSearch: true,
      //  render: (_, record) => <Input.Password defaultValue={record.userPassword} />
    },
    {
      title: '创建时间',
      hideInSearch: true,
      dataIndex: 'createTime',
    },
    {
      title: '系统角色',
      dataIndex: 'systemRole',
      hideInSearch: true,
      render: (_, record) => <Tag color="blue">{roleListMap[record.systemRole]?.name}</Tag>,
    },
    {
      title: '操作',
      width: 180,
      key: 'option',
      valueType: 'option',
      // 系统默认用户不可操作
      render: (_, record) =>
        record.id === 'user001'
          ? null
          : [
              <EditUserModal
                key="edit_user_modal"
                currentUser={record}
                roleList={Object.values(roleListMap)}
                onSubmit={onEditUser}
              />,
              <a
                key="user_delete"
                onClick={() => {
                  delUser(record.id);
                }}
              >
                删除
              </a>,
            ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<SYSTEMUSER.UserType, SYSTEMUSER.UserParams>
        actionRef={actionRef}
        columns={columns}
        request={async (params) => {
          const res = await getUserList(params);
          return {
            data: res.data.list,
            success: res.success,
            total: res.data.total,
          };
        }}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
        }}
        toolBarRender={() => [
          <AddUserModal
            roleList={Object.values(roleListMap)}
            onSubmit={onAddUser}
            key="add_user_modal"
          />,
        ]}
      />
    </PageContainer>
  );
};

export default UsersManage;
